﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ApplicationCombine.aspx.cs" Inherits="CRMWeb.Pages.Application.ApplicationCombine" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Application Combine</title>

    <script src="../../Scripts/jquery-1.8.0.min.js"></script>
    <link href="../../Css/CrmStyle.css" rel="stylesheet" />
    <link href="../../EasyUI/Themes/icon.css" rel="stylesheet" />
    <link id="newtheme" href="../../EasyUI/Themes/default/easyui.css" rel="stylesheet" />
    <script src="../../EasyUI/jquery.easyui.min.js"></script>
    <script src="../../Scripts/common.js"></script>
    <style type="text/css">
        .datagrid-header
        {
            min-height: 25px;
        }
        .hdnMsg {
            display:none;
            margin-left:20px;
            font-family:Arial;
            font-size:12px;
            font-weight:bold;
            position:absolute;
            
        }
    </style>
</head>

<body>

    <form id="form1" runat="server">
        <div id="pnlMain" title="Combine Application" class="easyui-panel" style="width: auto; height: auto; padding: 15px">
            <div class="fitem">
                <label style="width: auto">Client Name or ID :</label>
                 <input type="text" id="txtContactID" />
                 <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-search" id="btnSearch" onclick="getContactByNameOrId()"></a>

                <span id="lblMsg" style="color:green" class="hdnMsg">You could combine this client which has No application.</span>
                <span id="lblDupMsg" style="color:red" class="hdnMsg">Duplicated contact detected, please remove Duplicate first.</span>
            </div>
            <div class="fitem">
                <input type="hidden" id="hdncombine_app_id" />
                <input type="hidden" id="hdnOperator" runat="server" />
                <input type="hidden" id="hdncontactid" />
                <table id="dgAppLoan" class="easyui-datagrid" style="width: auto;" autorowheight="true" rownumbers="true" fitcolumns="true" singleselect="true">
                    <thead>
                        <tr>
                            <th field="cdate" width="30">Date Created</th>
                            <th field="age" data-options="formatter:calculateAge" width="25" sortable="true">Age</th>
                            <th field="DesiredAmount" width="20" data-options="formatter:ReplaceNumberWithCommas">Desired Amount</th>
                            <th field="app_result" width="45">Last Result</th>
                            <th field="ClientName" width="30">Name</th>
                            <th field="PurposeSummary" width="20">Product</th>
                            <th field="app_id">App.ID</th>
                            <th field="ContactId" data-options="formatter:formatContactProfile" width="20">ContactId</th>
                        </tr>
                    </thead>
                </table>
            </div>

            <div class="fitem">
                <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-cancel" id="btnCancel" onclick="window.close()">Cancel </a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-ok" id="btnConfirm" disabled="true" onclick="combineApplication()" style="float: right; margin-right: 10px">Confirm </a>
            </div>
        </div>
    </form>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#newtheme').attr('href', '../../EasyUI/Themes/' + getQuerystring('Theme', '') + '/easyui.css');

        });
        $(document).ready(function () {
            $('#pnlMain').panel('resize', {
                width: window.innerWidth - 2,
                height: window.innerHeight - 2
            });
        });
        function ReplaceNumberWithCommas(yourNumber) {
            if (yourNumber != null) {
                var components = yourNumber.toString().split(".");
                components[0] = components[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                return "$" + components.join(".");
            }
        }
        function calculateAge(value, row) {
            var date = null;
            if (value == null)
                date = new Date();
            else
                date = new Date(value);
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            var d = date.getDate();
            return getAge((m < 10 ? ('0' + m) : m) + '/' + (d < 10 ? ('0' + d) : d) + '/' + y);
        }
        function getQuerystring(key, defaultValue) {
            if (defaultValue == null) defaultValue = "";
            key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
            var qs = regex.exec(window.location.href);
            if (qs == null)
                return defaultValue;
            else {
                return qs[1];
            }
        }
        function formatContactProfile(value, row) {
            return "<a href='/Pages/Contact/ContactDetail.aspx?contact_id=" + value + "' target='_blank' style='cursor:pointer'>" + value + "</a>";
        }
        function getContactByNameOrId() {
            $('#dgAppLoan').datagrid('loadData', { "total": 0, "rows": [] });
            $('#lblMsg').hide();
            $('#lblDupMsg').hide();
            $('#hdncontactid').val('');

            var contactid = $('#txtContactID').val().trim();
            var intRegex = /^\d+$/;

            if (!intRegex.test(contactid)) {
                var splitNameList = contactid.split(" ");
                var splitNameLength = splitNameList.length;

                if (splitNameLength == 1) {
                    $.messager.alert('Morgan CRM', '<span style="color:red">Please input firstname and surname of Client. </span>');
                }
                else if (splitNameLength > 3) {
                    $.messager.alert('Morgan CRM', '<span style="color:red">Not valid name format. [FirstName]+space+[MiddleName]+space+[Surname] </span>');
                }
                else {
                    var firstname = splitNameList[0];
                    var surname = splitNameList[splitNameLength - 1];
                    var middlename = '';

                    if (splitNameLength == 3) {
                        middlename = splitNameList[1];
                    }
                    getContactIdByName(firstname,middlename,surname);
                }
            }
            else {
                getContactById(contactid);
            }
        }

        function getContactById(contactid) {
            $.ajax({
                url: '/WebServices/ApplicationInfo.ashx?method=IsValidContactForCombine',
                data: { app_id: getQuerystring('app_id', ''), contactid: contactid },
                success: function (response) {

                    if (response == '1') {
                        $('#hdncontactid').val(contactid);
                        $('#dgAppLoan').datagrid({
                            url: '/WebServices/ApplicationContact.ashx?method=GetAppLoanRecord&ContactID=' + contactid + '&noInApp=1',
                            onLoadSuccess: function (data) {
                                if (data.rows.length == 0) {
                                    $('#lblMsg').show();
                                    $('#hdncontactid').val(contactid);
                                }
                                else if (data.rows.length > 0) {
                                    $('#lblMsg').hide();
                                }
                                $('#btnConfirm').linkbutton('enable');
                            },
                            onDblClickRow: function (index, rowdata) {
                                combineApplication();
                            }
                        });
                    }
                    else if (response == '0')
                        $.messager.alert('Morgan CRM', '<span style="color:red"> Could not combine application with current contact </span>');
                    else if (response == '2')
                        $.messager.alert('Morgan CRM', '<span style="color:red"> This client does not exist </span>');
                    else if (response == '3')
                        $.messager.alert('Morgan CRM', '<span style="color:red"> This client has been combined with other application. </span>');
                }
            });
        }

        function getContactIdByName(firstname, middlename, surname) {
            var app_id = getQuerystring('app_id', '');
            var contactAmount = 0;
            var contactidList = [];
            $.ajax({
                url: '/WebServices/ApplicationInfo.ashx?method=GetContactIdByName',
                data: { app_id: app_id, firstname: firstname, middlename: middlename, surname: surname },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        contactidList[i] = rec.ContactId;
                    });
                    contactAmount = contactidList.length;
                    if (contactAmount == 0) {
                        $.messager.alert('Morgan CRM', '<span style="color:red"> The client does not exist or combined with other application. </span>');
                    }
                    else {
                        $('#dgAppLoan').datagrid({
                            url: '/WebServices/ApplicationContact.ashx?method=GetAppLoanRecordByName&app_id=' + app_id + '&firstname=' + firstname + '&middlename=' + middlename + '&surname=' + surname,
                            onLoadSuccess: function (data) {
                                $('#btnConfirm').linkbutton('enable');
                                if (data.rows.length == 0) {
                                    if (contactAmount > 1) {
                                        $('#lblMsg').hide();
                                        $('#lblDupMsg').show();
                                        $('#btnConfirm').linkbutton('disable');
                                    }
                                    else {
                                        $('#lblMsg').show();
                                        $('#lblDupMsg').hide();
                                        $('#hdncontactid').val(contactidList[0]);
                                    }
                                }
                                else if (data.rows.length > 0)
                                    $('#lblMsg').hide();
                            },
                            onDblClickRow: function (index, rowdata) {
                                combineApplication();
                            }
                        });
                    }
                }
            });
        }

        function getApplicationList() {
            var contactid = $('#txtContactID').val().trim();

            $.ajax({
                url: '/WebServices/ApplicationInfo.ashx?method=IsValidContactForCombine',
                data: { app_id: getQuerystring('app_id', ''), contactid: contactid },
                success: function (response) {
                    if (response == '1') {
                        $('#dgAppLoan').datagrid({
                            url: '/WebServices/ApplicationContact.ashx?method=GetAppLoanRecord&ContactID=' + contactid + '&noInApp=1',
                            onLoadSuccess: function (data) {
                                if (data.rows.length == 0)
                                    $('#lblMsg').show();
                                else if (data.rows.length > 0)
                                    $('#lblMsg').hide();
                                $('#btnConfirm').linkbutton('enable');
                            },
                            onDblClickRow: function (index, rowdata) {

                                combineApplication();
                            }

                        });
                    }
                    else if (response == '0')
                        $.messager.alert('Morgan CRM', '<span style="color:red"> Could not combine application with current contact </span>');
                    else if(response=='2')
                        $.messager.alert('Morgan CRM', '<span style="color:red"> This client does not exist </span>');
                }
            });
        }
        window.onresize = function () {
            $('#pnlMain').panel('resize', {
                width: window.innerWidth - 2,
                height: window.innerHeight - 2
            });
        }

        function combineApplication() {
            var combineappid = 0;
            var c_appid = getQuerystring('app_id', '');
            var contactid = $('#hdncontactid').val();
            var rows = $('#dgAppLoan').datagrid('getRows');
            if (rows.length > 0) {
                var row = $('#dgAppLoan').datagrid('getSelected');
                if (row) {
                    if (row.PurposeSummary == 'SACC') {
                        $.messager.alert('Morgan CRM', '<span style="color:red"> Could not combine SACC application </span>');
                        return;
                    }
                    else {
                        combineappid = row.app_id;
                        contactid = row.ContactId;
                    }
                    
                }
                else {
                    $.messager.alert('Morgan CRM', '<span style="color:red"> Please select row in Data Grid. </span>');
                    return;
                }
            }
           
            $.ajax({
                url: '/WebServices/ApplicationInfo.ashx?method=combineApplication',
                data: { currentAppID: c_appid, ContactID: contactid, combineAppID: combineappid, Operator: $('#hdnOperator').val() },
                success: function (response) {
                    if (response == 'True') {
                        window.opener.location.reload();
                        window.close();
                    }
                },
                error: function () {
                    $.messager.alert('Morgan CRM', 'Application Combine failed');
                }
            });
        }
    </script>
</body>

</html>
